const { app,screen,session,BrowserWindow,globalShortcut  } = require('electron')
const fs = require('fs')
if(!app) return;
var path = require("path")
var dlUtil = require("./download")

var preloadpath = path.join(__dirname, '../res/preload.js')
var iconpath = path.join(__dirname, '../res/sun.ico')

if (!fs.existsSync(preloadpath)) {
    preloadpath = path.join(__dirname, '../../res/preload.js')
    iconpath = path.join(__dirname, '../../res/sun.ico')
}




global.tipWin = null;
var winMgr = {
    showTradeWin(win,isShow){
        if (win) {
            if(isShow || !win.isVisible() ){
                if (win.isMinimized()) win.restore()
                win.show();
                win.focus();
            }else{
                win.hide();
            }
            try{
                global.createTrayMenu();
            }catch(ex){
    
            }
        }
    },
    createMainWin(){
        // 创建浏览器窗口
        const { width, height } = screen.getPrimaryDisplay().workAreaSize
        const win = new BrowserWindow({
            width: width,
            height: height,
            icon: iconpath,
            webPreferences: {
                // nodeIntegration: true,
                // nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
                // nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
                preload : preloadpath,
                enableRemoteModule: true,
                // webviewTag:true
            }
        })
        win.on("close",(event)=>{
            win.hide();
            event.preventDefault();
        })
        // 打开开发者工具
        // win.webContents.openDevTools()
        global.mainWin = win;
        // 并且为你的应用加载index.html
        // win.loadFile("http://127.0.0.1:8888/")
    },
    createTradeWin(){
        var winHeight=665;
        var winWidth = 1550;
        const { width, height } = screen.getPrimaryDisplay().workAreaSize
        var win = new BrowserWindow({ 
          width: winWidth, 
          height: winHeight,
          x: (width - winWidth)/2,
          y: height - winHeight+15,
          resizable: true,
          minimizable: true,
          maximizable: true,
          show: false,
          title:"godEye",
          icon: iconpath,
          webPreferences: {
            //   nodeIntegration: true,
            //   nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
            //   nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
              preload : preloadpath,
              enableRemoteModule: true,
            //   webviewTag:true
          }
        })
        win.on("close",(event)=>{
            event.preventDefault();
            win.hide();
            try{
                global.createTrayMenu();
            }catch(ex){

            }
        })
        global.tradeWin = win;
      
        // win.loadURL('http://localhost:8888/trade/main')
        
    },
    createTipWin(){
        const { width, height } = screen.getPrimaryDisplay().workAreaSize
        // console.info(width+"*"+height);
        var winHeight=130;
        var winWidth = 700;
        var win = new BrowserWindow({ 
          x: width - winWidth,
          y: height - winHeight,
          width: winWidth, 
          height: winHeight ,
          resizable: false,
          minimizable: false,
          maximizable: false,
          title:"god",
          autoHideMenuBar: true,
          frame: false,
          opacity: 0.7,
          transparent: true,
          alwaysOnTop: true,
          skipTaskbar: true,
          webPreferences: {
              nodeIntegration: true,
              nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
              nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
              preload : preloadpath,
              enableRemoteModule: true,
              webviewTag:true
          }
        })
        global.tipWin = win;
      
        win.setIgnoreMouseEvents(true)
        // win.setSkipTaskbar(skip)
        // Load a remote URL
        // win.loadURL('http://localhost:8888/tips/event')
        
    },
    createPopWin(){
        const { width, height } = screen.getPrimaryDisplay().workAreaSize
        // console.info(width+"*"+height);
        var winWidth = 240;
        var winHeight = 300;
        var x = width - winWidth;
        var y = parseInt((height - winHeight)/2);
        var win = new BrowserWindow({ 
          x: x,
          y: y,
          width: winWidth, 
        //   height: winHeight ,
        //   resizable: false,
          minimizable: false,
          maximizable: false,
        //   title:"pop",
          autoHideMenuBar: true,
          frame: false,

        //   useContentSize: true,
          show: false,
        //   opacity: 0.9,
          transparent: true,
          alwaysOnTop: true,
          skipTaskbar: true,
          webPreferences: {
            //   nodeIntegration: true,
            //   nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
            //   nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
              preload : preloadpath,
              enableRemoteModule: true,
              webviewTag:true
          }
        })
        global.popWin = win;
      
        // win.setIgnoreMouseEvents(true)
        // win.setSkipTaskbar(skip)
        // Load a remote URL
        // win.loadURL('http://localhost:8888/tips/event')
    },
    setReqHead(){
        // 需要拦截的URL地址 
        const head_filter = {
            urls: ['*://*/*']
        }    
        //不能全局设置,不然影响交易界面的请求头
        // console.info("set webRequest.onBeforeSendHeaders");
        // session.defaultSession.webRequest.onBeforeSendHeaders(head_filter, (details, callback) => {
        //     details.requestHeaders['Referer'] = 'unknow';
        //     details.requestHeaders['Origin'] = 'unknow';
        //     callback({ requestHeaders: details.requestHeaders });
        // })
        
        session.defaultSession.webRequest.onHeadersReceived(head_filter, (details, callback) => {
            details.responseHeaders['godEye-resp'] = 'up up up';
            details.responseHeaders["Access-Control-Allow-Credentials"] = true;
            if(details.responseHeaders["access-control-allow-origin"]){
            details.responseHeaders["access-control-allow-origin"] = '*';
            }else{
            details.responseHeaders["Access-Control-Allow-Origin"] = '*';
            }
    
            callback({ responseHeaders: details.responseHeaders })
        })
        // const content_filter = {
        //   urls: ['*://localhost:11201']
        // }    
        session.defaultSession.webRequest.onCompleted(head_filter, (details) => {
            var url = details.url;
            if(url.indexOf("kaipanla")!=-1) return;
            dlUtil.startHttpDl(url,details);
        })
    
        // session.defaultSession.webRequest.onResponseStarted(head_filter, (details) => {
        //   details.responseHeaders['godEye-resp'] = 'up up up';
        // })
  
    },
    getDFCFData(){
        if(winMgr.DFCFGeting){
            return;
        }
        winMgr.DFCFGeting = true;
        const win = new BrowserWindow({
            width: 800,
            height: 800,
            show: false,
            webPreferences: {
                // nodeIntegration: true,
                // nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
                // nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
                preload : preloadpath,
                enableRemoteModule: true,
                // webviewTag:true
            }
        })
        var urlList = [
            "https://jy.xzsec.com/Search/Position", //资金持仓
            "https://jy.xzsec.com/Search/Deal", //当日成交
            "https://jy.xzsec.com/Search/FundsFlow", //交割单
            "https://jy.xzsec.com/Finance/TTB/HisEarned", //基金收益
            "https://jy.xzsec.com/Transfer/HisTranList",  //银行明细
        ]
        var waittime = 1500;
        urlList.map((url,idx)=>{
            setTimeout(()=>{
                win.loadURL(url)
            },idx*waittime)
            if(idx==urlList.length-1){
                setTimeout(()=>{
                    winMgr.DFCFGeting = false;
                    global.showBox("东财数据获取成功");
                    win.close()
                },(idx+1)*waittime)
            }
        })
    },
    createDFCFWin(){
        const win = new BrowserWindow({
            width: 1200,
            height: 800,
            show: false,
            icon: iconpath,
            webPreferences: {
                // nodeIntegration: true,
                // nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
                // nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
                preload : preloadpath,
                enableRemoteModule: true,
                // webviewTag:true
            }
        })
        win.on("close",(event)=>{
            win.hide();
            event.preventDefault();
        })
        global.dfcfWin = win;
        // global.dfcfWin.maximize();
        // global.dfcfWin.hide();
        var url = "https://jy.xzsec.com/Search/Deal";
        win.loadURL(url)
        setInterval(() => {
            win.loadURL(url)
        }, 60*60*1000);
    },
    createKPLWin(){
        const win = new BrowserWindow({
            width: 1200,
            height: 800,
            show: false,
            icon: iconpath,
            webPreferences: {
                // nodeIntegration: true,
                // nodeIntegrationInWorker : true, //Boolean (可选) - 是否在Web工作器中启用了Node集成. 默认值为 false
                // nodeIntegrationInSubFrames : true, //Boolean (可选项)(实验性)，是否允许在子页面(iframe)或子窗口(child window)中集成Node.js； 预先加载的脚本会被注入到每一个iframe，你可以用 process.isMainFrame 来判断当前是否处于主框架（main frame）中
                preload : preloadpath,
                enableRemoteModule: true,
                // webviewTag:true
            }
        })
        win.on("close",(event)=>{
            win.hide();
            event.preventDefault();
        })
        global.kplWin = win;
        // global.dfcfWin.maximize();
        // global.dfcfWin.hide();
        var url = "https://www.kaipanla.com/capital/ranking";
        win.loadURL(url)
        // setInterval(() => {
        //     win.loadURL(url)
        // }, 60*60*1000);
    }
}
//

app.whenReady().then(()=>{
    winMgr.createMainWin();
    winMgr.createTipWin();
    winMgr.createTradeWin();
    winMgr.createPopWin();
    winMgr.createDFCFWin();
    winMgr.createKPLWin();
    winMgr.setReqHead();
    globalShortcut.register('Alt+X', () => {
        console.log('Alt+X is pressed')
        winMgr.showTradeWin(global.tradeWin);
    })
    globalShortcut.register('Alt+C', () => {
        console.log('Alt+C is pressed')
        winMgr.showTradeWin(global.mainWin);
    })
    globalShortcut.register('Alt+Space', () => {
        console.log('Alt+Space is pressed')
        winMgr.showTradeWin(global.popWin);
    })
    globalShortcut.register('Alt+D', () => {
        console.log('Alt+D is pressed')
        winMgr.showTradeWin(global.dfcfWin);
    })
    globalShortcut.register('Alt+K', () => {
        console.log('Alt+K is pressed')
        winMgr.showTradeWin(global.kplWin);
    })
    globalShortcut.register('Alt+Q', () => {
        console.log('Alt+Q is pressed')
        winMgr.getDFCFData();
    })
})
app.on('window-all-closed', () => {
// if (process.platform !== 'darwin') {
//   app.quit()
// }
})
app.on('before-quit', () => {
    if(global.tray){
        global.tray.destroy();
    }
})


app.on('second-instance', (event, commandLine, workingDirectory) => {
    // 当运行第二个实例时,将会聚焦到myWindow这个窗口
    winMgr.showTradeWin(global.tradeWin,true);
})
app.on('will-quit', () => {
    // 注销快捷键
    // globalShortcut.unregister('CommandOrControl+X')
  
    // 注销所有快捷键
    globalShortcut.unregisterAll()
})


